package com.emm.yixun.customer.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.basic.service.BusinessAbnormaService;
import com.emm.yixun.basic.service.CustomerService;
import com.emm.yixun.basic.service.DictionaryService;
import com.emm.yixun.basic.service.NeedReceiveRefundService;
import com.emm.yixun.basic.service.NoticeService;
import com.emm.yixun.basic.service.NoticeTemporaryService;
import com.emm.yixun.basic.service.PayDepositService;
import com.emm.yixun.basic.service.PriceSchemeService;
import com.emm.yixun.basic.service.ProjectRoomService;
import com.emm.yixun.basic.service.ProjectService;
import com.emm.yixun.basic.service.ReserveAreaService;
import com.emm.yixun.basic.service.SignedService;
import com.emm.yixun.basic.service.SubscribeService;
import com.emm.yixun.basic.service.UserService;
import com.emm.yixun.common.enums.ApplyMessageProcessKeyEnums;
import com.emm.yixun.common.model.BusinessAbnorma;
import com.emm.yixun.common.model.Customer;
import com.emm.yixun.common.model.Dictionary;
import com.emm.yixun.common.model.NeedReceiveRefund;
import com.emm.yixun.common.model.PayDeposit;
import com.emm.yixun.common.model.PriceScheme;
import com.emm.yixun.common.model.Project;
import com.emm.yixun.common.model.ProjectRoom;
import com.emm.yixun.common.model.ReserveArea;
import com.emm.yixun.common.model.Signed;
import com.emm.yixun.common.model.Subscribe;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.CustomerDto;
import com.emm.yixun.common.model.dto.DictionaryDto;
import com.emm.yixun.common.model.dto.NoticeTemporaryDto;
import com.emm.yixun.common.model.dto.UserDto;
import com.emm.yixun.common.model.enums.BusinessAbnormaEnum;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.model.enums.IsPaydepositEnum;
import com.emm.yixun.common.utils.MsgUtil;

@Service("sendMessageService")
public class SendMessageService {
	 @Autowired
	 private RuntimeService runtimeService;

	@Autowired
	private NoticeService noticeService;

	@Autowired
	private DictionaryService dictionaryService;

	@Autowired
	private PriceSchemeService priceSchemeService;

	@Autowired
	private ProjectService projectService;

	@Autowired
	private PayDepositService payDepositService;

	@Autowired
	private ProjectRoomService projectRoomService;

	@Autowired
	private CustomerService customerService;

	@Autowired
	private UserService userService;

	@Autowired
	private BusinessAbnormaService businessAbnormaService;

	@Autowired
	private SubscribeService subscribeService;

	@Autowired
	private SignedService signedService;

	@Autowired
	private ReserveAreaService reserveAreaService;
	
	@Autowired
	private NeedReceiveRefundService needReceiveRefundService;
	
	@Autowired
	private NoticeTemporaryService noticeTemporaryService;
	
	@Autowired
	private TaskService taskService; 
	
	public void applyDiscountMessageSend(String processInstanceId,String taskId,String nextNodeId,String processDefinitionKey,String businessKey,List<String> userIdList) {
		/*
		 * 功能：发送流程节点消息 1.收集发送消息信息 2.消息入库 3.推送极光
		 */
		try {
			List<User> userList = convertUserList(userIdList);
			if (userList.size() == 0)
				return;
			Map<String, String> noticeParamMap = createNoticeParamMap(
					processDefinitionKey, businessKey);
			String replaceValues=noticeParamMap.get("replaceValues");
			if(StringUtils.isNotBlank(replaceValues)){
				JSONObject object=JSON.parseObject(replaceValues);
				object.put(MsgUtil.NEXT_NODE_ID, nextNodeId==null?"":nextNodeId);
				object.put(MsgUtil.PROCESS_INSTANCE_ID, processInstanceId==null?"":processInstanceId);
				noticeParamMap.put("replaceValues", object.toJSONString());
			}
			// 2.消息入库
			String projectCode = noticeParamMap.get("projectCode");
			String projectName = noticeParamMap.get("projectName");
			String title = noticeParamMap.get("title");
			noticeService.createNotice(noticeParamMap,userList, null);
			
			
			//3.将消息存入临时推送表
			if(userList != null){
				for(User user: userList){
					NoticeTemporaryDto entity = new NoticeTemporaryDto();
					entity.setTitle(title);
					entity.setContent(noticeParamMap.get("sendMsg"));
					entity.setMerchantId(Long.parseLong(noticeParamMap.get("merchantId")));
					entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
					entity.setBusinessId(noticeParamMap.get("businessId"));
					entity.setReceiverId(user.getId());
					entity.setProjectCode(projectCode);
					entity.setProjectName(projectName);
					entity.setAction(title);
					entity.setPushType(noticeParamMap.get("noticeTempType"));
					entity.setCustomerId(noticeParamMap.get("customerId"));
					if(StringUtils.isNotBlank(taskId)){
						entity.setTaskId(taskId);
					}
					if(StringUtils.isNotBlank(noticeParamMap.get("tempType"))){
						entity.setTempType(noticeParamMap.get("tempType"));
					}
					entity.setRemindCategoryId(Long.valueOf(noticeParamMap.get("noticeDicId")));
					entity.setRemindCategory("审核申请");
					entity.setMsgOrder(1);
					
					noticeTemporaryService.create(entity);
				}
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void applyMessageSend(String processInstanceId,String nextNodeId,List<String> userIdList) {
		/*
		 * 功能：发送流程节点消息 1.收集发送消息信息 2.消息入库 3.推送极光
		 */
		try {
			List<User> userList = convertUserList(userIdList);
			if (userList.size() == 0)
				return;
			ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
			if (null == processInstance)
				return;
			// 1.收集发送消息信息
			String processDefinitionKey = processInstance
					.getProcessDefinitionKey();
			String businessKey = processInstance.getBusinessKey();
			Map<String, String> noticeParamMap = createNoticeParamMap(
					processDefinitionKey, businessKey);
			// 判断map参数个数
//			if (noticeParamMap.size() != 11)
//				return;
			//设置跳转待办参数
			String replaceValues=noticeParamMap.get("replaceValues");
			if(StringUtils.isNotBlank(replaceValues)){
				JSONObject object=JSON.parseObject(replaceValues);
				object.put(MsgUtil.NEXT_NODE_ID, nextNodeId==null?"":nextNodeId);
				object.put(MsgUtil.PROCESS_INSTANCE_ID, processInstanceId==null?"":processInstanceId);
				noticeParamMap.put("replaceValues", object.toJSONString());
			}
			// 2.消息入库
			String projectCode = noticeParamMap.get("projectCode");
			String projectName = noticeParamMap.get("projectName");
			String title = noticeParamMap.get("title");
			noticeService.createNotice(noticeParamMap,
					userList, null);
			// 3.推送极光
			//noticeService.pushMsg(projectCode, projectName, noticeDto, title);
			
			//查询taskID
			Task cruTask=taskService.createTaskQuery().processInstanceId(processInstanceId).taskDefinitionKey(nextNodeId).singleResult();
			
			//3.将消息存入临时推送表
			if(userList != null){
				for(User user: userList){
					NoticeTemporaryDto entity = new NoticeTemporaryDto();
					entity.setTitle(title);
					entity.setContent(noticeParamMap.get("sendMsg"));
					entity.setMerchantId(Long.parseLong(noticeParamMap.get("merchantId")));
					entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
					entity.setBusinessId(noticeParamMap.get("businessId"));
					entity.setReceiverId(user.getId());
					entity.setProjectCode(projectCode);
					entity.setProjectName(projectName);
					entity.setAction(title);
					entity.setPushType(noticeParamMap.get("noticeTempType"));
					entity.setCustomerId(noticeParamMap.get("customerId"));
					if(cruTask != null){
						entity.setTaskId(cruTask.getId());
					}
					if(StringUtils.isNotBlank(noticeParamMap.get("tempType"))){
						entity.setTempType(noticeParamMap.get("tempType"));
					}
					entity.setRemindCategoryId(Long.valueOf(noticeParamMap.get("noticeDicId")));
					entity.setRemindCategory("审核申请");
					entity.setMsgOrder(1);
					
					noticeTemporaryService.create(entity);
				}
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private List<User> convertUserList(List<String> userIdList) {
		List<User> userList = new ArrayList<User>();
		for (String userId : userIdList) {
			User user = new User();
			user.setId(Long.valueOf(userId));
			userList.add(user);
		}
		return userList;
	}

	private Map<String, String> createNoticeParamMap(
			String processDefinitionKey, String businessKey) {
		ApplyMessageProcessKeyEnums ampke = ApplyMessageProcessKeyEnums
				.getByNo(processDefinitionKey);
		if (null == ampke)
			return null;
		// 查询模板
		String enumsDes = ampke.getDes();
		String[] enumsDesArray = enumsDes.split(";");
		String messageTitle = enumsDesArray[0];
		String dictionaryValue = enumsDesArray[1];
		DictionaryDto dicDto = new DictionaryDto();
		dicDto.setDictionaryValue(dictionaryValue);
		Dictionary dic = dictionaryService.selectByDto(dicDto);
		if (null == dic)
			return null;
		Map<String, String> noticeParamMap = new HashMap<String, String>();
		noticeParamMap.put("noticeDicId", String.valueOf(dic.getId()));
		noticeParamMap.put("noticeTempType", dictionaryValue);
		noticeParamMap.put("title", messageTitle);
		String msgTemp = dic.getDictionaryName();
		Long businessId = Long.valueOf(businessKey);
		noticeParamMap.put("businessId", businessId+"");
		if (processDefinitionKey
				.equals(ApplyMessageProcessKeyEnums.PROCESS_KEY_1.getNo())) {
			collectPriceScheme(businessId, msgTemp, noticeParamMap);
		} else if (processDefinitionKey
				.equals(ApplyMessageProcessKeyEnums.PROCESS_KEY_2.getNo())) {
			String msgTemp_sx = "价格方案失效审批申请。方案名称：${schemeName}；操作人：${agent}";
			collectPriceSchemeInvalid(businessId, msgTemp_sx, noticeParamMap);
		} else if (processDefinitionKey
				.equals(ApplyMessageProcessKeyEnums.PROCESS_KEY_3.getNo())) {
			collectCusPayDeposit(businessId, msgTemp, noticeParamMap);
		} else if (processDefinitionKey
				.equals(ApplyMessageProcessKeyEnums.PROCESS_KEY_4.getNo())) {
			collectCusPayDepositRetreat(businessId, msgTemp, noticeParamMap);
		} else if (processDefinitionKey
				.equals(ApplyMessageProcessKeyEnums.PROCESS_KEY_5.getNo())) {
			collectCusSubscribe(businessId, msgTemp, noticeParamMap);
		} else if (processDefinitionKey
				.equals(ApplyMessageProcessKeyEnums.PROCESS_KEY_6.getNo())) {
			collectCusSubscribeRetreat(businessId, msgTemp, noticeParamMap);
		} else if (processDefinitionKey
				.equals(ApplyMessageProcessKeyEnums.PROCESS_KEY_7.getNo())) {
			collectCusCubscribeChangeHouse(businessId, msgTemp, noticeParamMap);
		} else if (processDefinitionKey
				.equals(ApplyMessageProcessKeyEnums.PROCESS_KEY_8.getNo())) {
			collectCusCubscribeAndSignedChangeName(businessId, msgTemp,
					noticeParamMap);
		} else if (processDefinitionKey
				.equals(ApplyMessageProcessKeyEnums.PROCESS_KEY_9.getNo())) {
			String msgTemp_yqqy = "延期签约(15天内）审批申请。房号：${roomName}；客户：${customer}；归属人：${agent}";
			collectCusCubscribeDelaySinged(businessId, msgTemp_yqqy, noticeParamMap);
		} else if (processDefinitionKey
				.equals(ApplyMessageProcessKeyEnums.PROCESS_KEY_10.getNo())) {
			String msgTemp_yqqy2 = "延期签约(15~30天）审批申请。房号：${roomName}；客户：${customer}；归属人：${agent}";
			collectCusCubscribeDelaySinged(businessId, msgTemp_yqqy2, noticeParamMap);
		} else if (processDefinitionKey
				.equals(ApplyMessageProcessKeyEnums.PROCESS_KEY_11.getNo())) {
			String msgTemp_yqqy3 = "延期签约(30天以上）审批申请。房号：${roomName}；客户：${customer}；归属人：${agent}";
			collectCusCubscribeDelaySinged(businessId, msgTemp_yqqy3, noticeParamMap);
		} else if (processDefinitionKey
				.equals(ApplyMessageProcessKeyEnums.PROCESS_KEY_12.getNo())) {
			collectCusSigned(businessId, msgTemp, noticeParamMap);
		} else if (processDefinitionKey
				.equals(ApplyMessageProcessKeyEnums.PROCESS_KEY_13.getNo())) {
			collectCusSignedDiscount(businessId, msgTemp, noticeParamMap);
		} else if (processDefinitionKey
				.equals(ApplyMessageProcessKeyEnums.PROCESS_KEY_14.getNo())) {
			collectCusSignedChangeHouse(businessId, msgTemp, noticeParamMap);
		} else if (processDefinitionKey
				.equals(ApplyMessageProcessKeyEnums.PROCESS_KEY_15.getNo())) {
			collectCusSignedCheckOut(businessId, msgTemp, noticeParamMap);
		} else if (processDefinitionKey
				.equals(ApplyMessageProcessKeyEnums.PROCESS_KEY_16.getNo())) {
			collectDealReserveArea(businessId, msgTemp, noticeParamMap);
		} else if (processDefinitionKey
				.equals(ApplyMessageProcessKeyEnums.PROCESS_KEY_17.getNo())) {
			collectCusSubscribeDiscount(businessId, msgTemp, noticeParamMap);
		} else if (processDefinitionKey
				.equals(ApplyMessageProcessKeyEnums.PROCESS_KEY_18.getNo())) {
			String msgTemp_yqkyq = "应收款延期(15天内）审批申请。房号：${roomName}；客户：${customer}；归属人：${agent}";
			collectNeedDelay(businessId, msgTemp_yqkyq, noticeParamMap);
		} else if (processDefinitionKey
				.equals(ApplyMessageProcessKeyEnums.PROCESS_KEY_19.getNo())) {
			String msgTemp_yqkyq2 = "应收款延期(15~30天）审批申请。房号：${roomName}；客户：${customer}；归属人：${agent}";
			collectNeedDelay(businessId, msgTemp_yqkyq2, noticeParamMap);
		} else if (processDefinitionKey
				.equals(ApplyMessageProcessKeyEnums.PROCESS_KEY_20.getNo())) {
			String msgTemp_yqkyq3 = "应收款延期(30天以上）审批申请。房号：${roomName}；客户：${customer}；归属人：${agent}";
			collectNeedDelay(businessId, msgTemp_yqkyq3, noticeParamMap);
		}
		
		return noticeParamMap;
	}
	
	//应收款延期
	private void collectNeedDelay(Long businessId, String msgTemp,
			Map<String, String> noticeParamMap){
		BusinessAbnorma businessAbnorma = businessAbnormaService.selectById(businessId);
		NeedReceiveRefund needReceiveRefund = needReceiveRefundService.selectById(businessAbnorma.getBusinessId());
/*		NeedReceiveRefundDto needReceiveRefundDto = new NeedReceiveRefundDto();
		needReceiveRefundDto.setRelationId(businessAbnorma.getBusinessId());
		NeedReceiveRefund needReceiveRefund = needReceiveRefundService.selectByDto(needReceiveRefundDto);*/
		if(needReceiveRefund == null){
			return;
		}
		// 房间名称
		Long roomId = null;
		String roomName = "";
		String projectCode = "";
		String projectName = "";
		ProjectRoom projectRoom = projectRoomService.selectById(needReceiveRefund.getRoomId());
		if (null != projectRoom) {
			roomId = projectRoom.getId();
			roomName = projectRoom.getCombinedName();
		}
		Project project = projectService.selectById(projectRoom.getProjectId());
		if (null != project) {
			projectCode = project.getProjectCode();
			projectName = project.getProjectName();
		}
		
		Customer customer = customerService.selectById(needReceiveRefund.getCustomerId());
		String operateUser = operateUser(customer.getUserCode()); //查询归属人

		String sendMsg = msgTemp.replace("${roomName}", roomName)
				.replace("${customer}", customer.getCustomerName())
				.replace("${agent}", operateUser);
		noticeParamMap.put("sendMsg", sendMsg);
		noticeParamMap.put("merchantId",
				String.valueOf(needReceiveRefund.getMerchantId()));
		noticeParamMap.put("projectCode", projectCode);
		noticeParamMap.put("projectName", projectName);
		noticeParamMap.put("userCode", needReceiveRefund.getUserCode());
		noticeParamMap.put("accessCode", needReceiveRefund.getAccessCode());
		noticeParamMap.put("createUserId",
				String.valueOf(needReceiveRefund.getCreateUserId()));
		noticeParamMap.put("customerId", customer.getId()+"");
		noticeParamMap.put("tempType", "1");

		Map<String, String> replaceValuesMap = new HashMap<String, String>();
		replaceValuesMap.put(MsgUtil.ROOM_ID,
				roomId == null ? "" : String.valueOf(roomId));
		replaceValuesMap.put(MsgUtil.ROOM_NAME, roomName);
		replaceValuesMap.put(MsgUtil.CUSTOMER_ID, "");
		replaceValuesMap.put(MsgUtil.CUSTOMER_NAME, "");
		replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
		replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
		replaceValuesMap.put(MsgUtil.BUSINESS_ID, businessId+"");
		noticeParamMap.put("replaceValues",
				MsgUtil.getReplaceValues(replaceValuesMap));
		
	}

	// 面积补差审批
	private void collectDealReserveArea(Long businessId, String msgTemp,
			Map<String, String> noticeParamMap) {
		ReserveArea reserveArea = reserveAreaService.selectById(businessId);
		if (null == reserveArea)
			return;
		String operateUser = "";
		if (null != reserveArea.getCreateUserId()) {
			User user = userService.selectById(reserveArea.getCreateUserId());
			if (user != null) {
				operateUser = user.getUserName();
			}
		}
		Signed signed = signedService.selectById(reserveArea.getSignedId());
		if(null==signed)return;
		// 房间名称
		Long roomId = null;
		String roomName = "";
		String projectCode = "";
		String projectName = "";
		Project project = projectService.selectById(signed.getProjectId());
		if (null != project) {
			projectCode = project.getProjectCode();
			projectName = project.getProjectName();
		}
		ProjectRoom projectRoom = projectRoomService.selectById(signed
				.getRoomId());
		if (null != projectRoom) {
			roomId = projectRoom.getId();
			roomName = projectRoom.getCombinedName();
		}
		Customer customer = customerService.selectById(signed.getCustomerId());

		String sendMsg = msgTemp.replace("${roomName}", roomName)
				.replace("${customer}", customer.getCustomerName())
				.replace("${agent}", operateUser);
		noticeParamMap.put("sendMsg", sendMsg);
		noticeParamMap.put("merchantId",
				String.valueOf(reserveArea.getMerchantId()));
		noticeParamMap.put("projectCode", projectCode);
		noticeParamMap.put("projectName", projectName);
		noticeParamMap.put("userCode", reserveArea.getUserCode());
		noticeParamMap.put("accessCode", reserveArea.getAccessCode());
		noticeParamMap.put("createUserId",
				String.valueOf(reserveArea.getCreateUserId()));
		noticeParamMap.put("customerId", customer.getId()+"");
		noticeParamMap.put("tempType", "1");

		Map<String, String> replaceValuesMap = new HashMap<String, String>();
		replaceValuesMap.put(MsgUtil.ROOM_ID,
				roomId == null ? "" : String.valueOf(roomId));
		replaceValuesMap.put(MsgUtil.ROOM_NAME, roomName);
		replaceValuesMap.put(MsgUtil.CUSTOMER_ID, "");
		replaceValuesMap.put(MsgUtil.CUSTOMER_NAME, "");
		replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
		replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
		noticeParamMap.put("replaceValues",
				MsgUtil.getReplaceValues(replaceValuesMap));
	}

	// 签约退房审批
	private void collectCusSignedCheckOut(Long businessId, String msgTemp,
			Map<String, String> noticeParamMap) {
		BusinessAbnorma businessAbnorma = businessAbnormaService
				.selectById(businessId);
		if (null == businessAbnorma)
			return;
		collectCusSignedDiscount(businessAbnorma.getBusinessId(), msgTemp,
				noticeParamMap);
	}

	// 签约换房审批
	private void collectCusSignedChangeHouse(Long businessId, String msgTemp,
			Map<String, String> noticeParamMap) {
		collectCusSigned(businessId, msgTemp, noticeParamMap);
	}

	// 签约折扣审批
	private void collectCusSignedDiscount(Long businessId, String msgTemp,
			Map<String, String> noticeParamMap) {
		collectCusSigned(businessId, msgTemp, noticeParamMap);
	}

	// 签约审批
	private void collectCusSigned(Long businessId, String msgTemp,
			Map<String, String> noticeParamMap) {
		Signed signed = signedService.selectById(businessId);
		if (null == signed)
			return;
		Long roomId = null;
		Long customerId = null;
		String roomName = "";
		String customerName = "";
		String projectCode = "";
		String projectName = "";
		Project project = projectService.selectById(signed.getProjectId());
		if (null != project) {
			projectCode = project.getProjectCode();
			projectName = project.getProjectName();
		}
		ProjectRoom projectRoom = projectRoomService.selectById(signed
				.getRoomId());
		if (null != projectRoom) {
			roomId = projectRoom.getId();
			roomName = projectRoom.getCombinedName();
		}
		String userName = "";
		Customer customer = customerService.selectById(signed.getCustomerId());
		if (null != customer) {
			customerName = customer.getCustomerName();
			customerId = customer.getId();
			userName = operateUser(customer.getUserCode()); //归属人
		}
		
//		TransactionRelationDto transactionRelationDto = new TransactionRelationDto();
//		transactionRelationDto.setBusinessId(signed.getId());
//		transactionRelationDto.setRelationType("6");
//		List<TransactionRelation> transactionRelationList = transactionRelationService
//				.selectListByDto(transactionRelationDto);
//		if (transactionRelationList.size() > 0) {
//			for (int i = 0; i < transactionRelationList.size(); i++) {
//				User user = userService.selectById(transactionRelationList.get(
//						i).getRelationAgentid());
//				if (user.getUserName() != null
//						&& !"".equals(user.getUserName())) {
//					if (transactionRelationList.size() == 1) {
//						userName = user.getUserName();
//					} else {
//						userName += "；经纪人" + (i + 1) + "：" + user.getUserName();
//					}
//				}
//			}
//		}
		String sendMsg = msgTemp.replace("${roomName}", roomName)
				.replace("${customer}", customerName)
				.replace("${agent}", userName);
		noticeParamMap.put("sendMsg", sendMsg);
		noticeParamMap
				.put("merchantId", String.valueOf(signed.getMerchantId()));
		noticeParamMap.put("projectCode", projectCode);
		noticeParamMap.put("projectName", projectName);
		noticeParamMap.put("userCode", signed.getUserCode());
		noticeParamMap.put("accessCode", signed.getAccessCode());
		noticeParamMap.put("createUserId",
				String.valueOf(signed.getCreateUserId()));
		noticeParamMap.put("customerId", customer.getId()+"");
		noticeParamMap.put("tempType", "1");

		Map<String, String> replaceValuesMap = new HashMap<String, String>();
		replaceValuesMap.put(MsgUtil.ROOM_ID,
				roomId == null ? "" : String.valueOf(roomId));
		replaceValuesMap.put(MsgUtil.ROOM_NAME, roomName);
		replaceValuesMap.put(MsgUtil.CUSTOMER_ID, customerId == null ? ""
				: String.valueOf(customerId));
		replaceValuesMap.put(MsgUtil.CUSTOMER_NAME, customerName);
		replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
		replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
		noticeParamMap.put("replaceValues",
				MsgUtil.getReplaceValues(replaceValuesMap));
	}

	// 延期签约审批
	private void collectCusCubscribeDelaySinged(Long businessId,
			String msgTemp, Map<String, String> noticeParamMap) {
		BusinessAbnorma businessAbnorma = businessAbnormaService
				.selectById(businessId);
		if (null == businessAbnorma)
			return;
		collectCusSubscribe(businessAbnorma.getBusinessId(), msgTemp,
				noticeParamMap);
	}

	// 更名审批
	private void collectCusCubscribeAndSignedChangeName(Long businessId,
			String msgTemp, Map<String, String> noticeParamMap) {
		BusinessAbnorma businessAbnorma = businessAbnormaService
				.selectById(businessId);
		if (null == businessAbnorma)
			return;
		if (businessAbnorma.getBusinessType().equals(
				BusinessAbnormaEnum.BusinessAbnorma_6.getNo())) {
			// 签约
			collectCusSigned(businessAbnorma.getBusinessId(), msgTemp,
					noticeParamMap);
		} else {
			// 认购
			collectCusSubscribe(businessAbnorma.getBusinessId(), msgTemp,
					noticeParamMap);
		}

	}

	// 认购换房审批
	private void collectCusCubscribeChangeHouse(Long businessId,
			String msgTemp, Map<String, String> noticeParamMap) {
		collectCusSubscribe(businessId, msgTemp, noticeParamMap);
	}

	// 退认购审批
	private void collectCusSubscribeRetreat(Long businessId, String msgTemp,
			Map<String, String> noticeParamMap) {
		BusinessAbnorma businessAbnorma = businessAbnormaService
				.selectById(businessId);
		if (null == businessAbnorma)
			return;
		collectCusSubscribe(businessAbnorma.getBusinessId(), msgTemp,
				noticeParamMap);
	}

	// 认购折扣审批
	private void collectCusSubscribeDiscount(Long businessId, String msgTemp,
			Map<String, String> noticeParamMap) {
		collectCusSubscribe(businessId, msgTemp, noticeParamMap);
	}

	// 认购
	private void collectCusSubscribe(Long businessId, String msgTemp,
			Map<String, String> noticeParamMap) {
		Subscribe subscribe = subscribeService.selectById(businessId);
		if (null == subscribe)
			return;
		String userName = "";
//		TransactionRelationDto transactionRelationDto = new TransactionRelationDto();
//		transactionRelationDto.setBusinessId(businessId);
//		transactionRelationDto.setRelationType("5");
//		List<TransactionRelation> transactionRelationList = transactionRelationService
//				.selectListByDto(transactionRelationDto);
//		if (transactionRelationList.size() > 0) {
//			for (int i = 0; i < transactionRelationList.size(); i++) {
//				User user = userService.selectById(transactionRelationList.get(
//						i).getRelationAgentid());
//				if (user.getUserName() != null
//						&& !"".equals(user.getUserName())) {
//					if (transactionRelationList.size() == 1) {
//						userName = user.getUserName();
//					} else {
//						userName += "；经纪人" + (i + 1) + "：" + user.getUserName();
//					}
//				}
//			}
//		}
		Long roomId = null;
		Long customerId = null;
		String roomName = "";
		String customerName = "";
		String projectCode = "";
		String projectName = "";
		Project project = projectService.selectById(subscribe.getProjectId());
		if (null != project) {
			projectCode = project.getProjectCode();
			projectName = project.getProjectName();
		}
		ProjectRoom projectRoom = projectRoomService.selectById(subscribe
				.getRoomId());
		if (null != projectRoom) {
			roomId = projectRoom.getId();
			roomName = projectRoom.getCombinedName();
		}
		Customer customer = customerService.selectById(subscribe
				.getCustomerId());
		if (null != customer) {
			customerName = customer.getCustomerName();
			customerId = customer.getId();
			userName = operateUser(customer.getUserCode()); //归属人
		}
		String sendMsg = msgTemp.replace("${roomName}", roomName)
				.replace("${customer}", customerName)
				.replace("${agent}", userName);
		noticeParamMap.put("sendMsg", sendMsg);
		noticeParamMap.put("merchantId",
				String.valueOf(subscribe.getMerchantId()));
		noticeParamMap.put("projectCode", projectCode);
		noticeParamMap.put("projectName", projectName);
		noticeParamMap.put("userCode", subscribe.getUserCode());
		noticeParamMap.put("accessCode", subscribe.getAccessCode());
		noticeParamMap.put("createUserId",
				String.valueOf(subscribe.getCreateUserId()));
		noticeParamMap.put("customerId", customer.getId()+"");
		noticeParamMap.put("tempType", "1");
		
		Map<String, String> replaceValuesMap = new HashMap<String, String>();
		replaceValuesMap.put(MsgUtil.ROOM_ID,
				roomId == null ? "" : String.valueOf(roomId));
		replaceValuesMap.put(MsgUtil.ROOM_NAME, roomName);
		replaceValuesMap.put(MsgUtil.CUSTOMER_ID, customerId == null ? ""
				: String.valueOf(customerId));
		replaceValuesMap.put(MsgUtil.CUSTOMER_NAME, customerName);
		replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
		replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
		noticeParamMap.put("replaceValues",
				MsgUtil.getReplaceValues(replaceValuesMap));
	}

	// 退认筹
	private void collectCusPayDepositRetreat(Long businessId, String msgTemp,
			Map<String, String> noticeParamMap) {
		BusinessAbnorma businessAbnorma = businessAbnormaService
				.selectById(businessId);
		if (null == businessAbnorma)
			return;
		collectCusPayDeposit(businessAbnorma.getBusinessId(), msgTemp,
				noticeParamMap);
	}

	private void collectCusPayDeposit(Long payDepositId, String msgTemp,
			Map<String, String> noticeParamMap) {
		PayDeposit payDeposit = payDepositService.selectById(payDepositId);
		if (null == payDeposit)
			return;
		Long roomId = null;
		Long customerId = null;
		String roomName = "";
		String customerName = "";
		String projectCode = "";
		String projectName = "";
		String operateUser = "";
		Project project = projectService.selectById(payDeposit.getProjectId());
		if (null != project) {
			projectCode = project.getProjectCode();
			projectName = project.getProjectName();
		}
		Customer customer = customerService.selectById(payDeposit
				.getCustomerId());
		if (null != customer) {
			customerId = customer.getId();
			customerName = customer.getCustomerName();
			operateUser = operateUser(customer.getUserCode()); //归属人
		}
//		if (null != payDeposit.getAgentId()) {
//			User user = userService.selectById(payDeposit.getAgentId());
//			if (user != null) {
//				operateUser = user.getUserName();
//			}
//		}
		if (IsPaydepositEnum.NO.getNo().equals(payDeposit.getIsPaydeposit())) {
			// 有房认筹
			ProjectRoom projectRoom = projectRoomService.selectById(payDeposit
					.getRoomId());
			if (null != projectRoom) {
				roomId = projectRoom.getId();
				roomName = projectRoom.getCombinedName();
			}
		} else {
			roomName = "无";
		}
		String sendMsg = msgTemp.replace("${roomName}", roomName)
				.replace("${customer}", customerName)
				.replace("${agent}", operateUser);
		noticeParamMap.put("sendMsg", sendMsg);
		noticeParamMap.put("merchantId",
				String.valueOf(payDeposit.getMerchantId()));
		noticeParamMap.put("projectCode", projectCode);
		noticeParamMap.put("projectName", projectName);
		noticeParamMap.put("userCode", payDeposit.getUserCode());
		noticeParamMap.put("accessCode", payDeposit.getAccessCode());
		noticeParamMap.put("createUserId",
				String.valueOf(payDeposit.getCreateUserId()));
		noticeParamMap.put("customerId", customer.getId()+"");
		noticeParamMap.put("tempType", "1");
		
		Map<String, String> replaceValuesMap = new HashMap<String, String>();
		replaceValuesMap.put(MsgUtil.ROOM_ID,
				roomId == null ? "" : String.valueOf(roomId));
		replaceValuesMap.put(MsgUtil.ROOM_NAME, roomName);
		replaceValuesMap.put(MsgUtil.CUSTOMER_ID, customerId == null ? ""
				: String.valueOf(customerId));
		replaceValuesMap.put(MsgUtil.CUSTOMER_NAME, customerName);
		replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
		replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
		noticeParamMap.put("replaceValues",
				MsgUtil.getReplaceValues(replaceValuesMap));
	}

	private void collectPriceSchemeInvalid(Long priceSchemeId, String msgTemp,
			Map<String, String> noticeParamMap) {
		//priceSchemeId 异常流程主键ID
		BusinessAbnorma businessAbnorma = businessAbnormaService.selectById(priceSchemeId);
		PriceScheme priceScheme = priceSchemeService.selectById(businessAbnorma.getBusinessId());
		if (null == priceScheme)
			return;
		Project project = projectService.selectById(priceScheme.getProjectId());
		
		//查询操作人
		String operateUser = "";
		if(priceScheme.getCreateUserId() != null){
			User user = userService.selectById(priceScheme.getCreateUserId());
			if(user != null){
				operateUser = user.getUserName();
			}
		}
		//查询客户
		/*String customerName = "";*/
		String customerId = "";
		if(priceScheme.getUserCode() != null){
			CustomerDto entity = new CustomerDto();
			entity.setCustomerCode(priceScheme.getUserCode());
			Customer customer = customerService.selectByDto(entity);
			if(customer != null){
				/*customerName = customer.getCustomerName();*/
				customerId = customer.getId()+"";
			}
		}
		
		String sendMsg = msgTemp.replace("${schemeName}",priceScheme.getName())
				/*.replace("${customer}",customerName)*/
				.replace("${agent}",operateUser);
		noticeParamMap.put("sendMsg", sendMsg);
		noticeParamMap.put("merchantId",
				String.valueOf(priceScheme.getMerchantId()));
		noticeParamMap.put("projectCode", project.getProjectCode());
		noticeParamMap.put("projectName",
				project == null ? "" : project.getProjectName());
		noticeParamMap.put("userCode", priceScheme.getUserCode());
		noticeParamMap.put("accessCode", priceScheme.getAccessCode());
		noticeParamMap.put("createUserId",
				String.valueOf(priceScheme.getCreateUserId()));
		noticeParamMap.put("customerId", customerId);
		noticeParamMap.put("tempType", "1");
		
		Map<String, String> replaceValuesMap = new HashMap<String, String>();
		replaceValuesMap.put(MsgUtil.ROOM_ID, "");
		replaceValuesMap.put(MsgUtil.ROOM_NAME, "");
		replaceValuesMap.put(MsgUtil.CUSTOMER_ID, "");
		replaceValuesMap.put(MsgUtil.CUSTOMER_NAME, "");
		replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID,
				String.valueOf(priceSchemeId));
		replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME,
				priceScheme.getSecheme());
		noticeParamMap.put("replaceValues",
				MsgUtil.getReplaceValues(replaceValuesMap));

	}

	private void collectPriceScheme(Long priceSchemeId, String msgTemp,
			Map<String, String> noticeParamMap) {
		PriceScheme priceScheme = priceSchemeService.selectById(priceSchemeId);
		if (null == priceScheme)
			return;
		Project project = projectService.selectById(priceScheme.getProjectId());
		
		//查询操作人
		String operateUser = "";
		if(priceScheme.getCreateUserId() != null){
			User user = userService.selectById(priceScheme.getCreateUserId());
			if(user != null){
				operateUser = user.getUserName();
			}
		}
		//查询客户
		/*String customerName = "";*/
		String customerId = "";
		if(priceScheme.getUserCode() != null){
			CustomerDto entity = new CustomerDto();
			entity.setCustomerCode(priceScheme.getUserCode());
			Customer customer = customerService.selectByDto(entity);
			if(customer != null){
				/*customerName = customer.getCustomerName();*/
				customerId = customer.getId()+"";
			}
		}
		String sendMsg = msgTemp.replace("${schemeName}",priceScheme.getName())
				/*.replace("${customer}",customerName)*/
				.replace("${agent}",operateUser);
		noticeParamMap.put("sendMsg", sendMsg);
		noticeParamMap.put("merchantId",
				String.valueOf(priceScheme.getMerchantId()));
		noticeParamMap.put("projectCode", project.getProjectCode());
		noticeParamMap.put("projectName",
				project == null ? "" : project.getProjectName());
		noticeParamMap.put("userCode", priceScheme.getUserCode());
		noticeParamMap.put("accessCode", priceScheme.getAccessCode());
		noticeParamMap.put("createUserId",
				String.valueOf(priceScheme.getCreateUserId()));
		noticeParamMap.put("customerId", customerId);
		noticeParamMap.put("tempType", "1");
		
		Map<String, String> replaceValuesMap = new HashMap<String, String>();
		replaceValuesMap.put(MsgUtil.ROOM_ID, "");
		replaceValuesMap.put(MsgUtil.ROOM_NAME, "");
		replaceValuesMap.put(MsgUtil.CUSTOMER_ID, "");
		replaceValuesMap.put(MsgUtil.CUSTOMER_NAME, "");
		replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID,
				String.valueOf(priceSchemeId));
		replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME,
				priceScheme.getSecheme());
		noticeParamMap.put("replaceValues",
				MsgUtil.getReplaceValues(replaceValuesMap));
	}

	//获取归属人
	public String operateUser(String UserCode){
		String operateUser = "";
		if (null != UserCode) {
			UserDto userDto = new UserDto();
			userDto.setUserCode(UserCode);
			User user = userService.selectByDto(userDto);
			if (user != null) {
				operateUser = user.getUserName();
			}
		}
		return operateUser;
	}
}
